package com.free4inno.knowledgems.interceptor;

import com.free4inno.knowledgems.constants.UserConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.free4inno.knowledgems.utils.CompleteUriUtils.getCompleteUri;

/**
 * Author HUYUZHU.
 * Date 2020/10/15 16:00.
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //获取被拦截的uri
        String completeUri = getCompleteUri(httpServletRequest);
        //存入session
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute(UserConstants.COMPLETE_URI, completeUri);
        //log.info(completeUri);

        //判断是否是登陆状态
        Object user = session.getAttribute("account");
        if (user == null || user.equals("")) {
            httpServletResponse.sendRedirect("/login");
            return false;
        } else {
            session.removeAttribute(UserConstants.COMPLETE_URI);
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
